package esi.t2no1.ws.interceptor;

import static esi.t2no1.util.WsUtil.extractLogMessageParts;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import org.apache.cxf.binding.soap.SoapFault;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingMessage;
import org.apache.cxf.message.Message;
import org.springframework.beans.factory.annotation.Autowired;

import esi.t2no1.dao.message.MessageDAO;
import esi.t2no1.util.WsUtil;

/**
 * Interceptor that logs all outbound SOAP messages to database
 * 
 * @author Kaarel Jõgeva
 */
public class DbLoggingInInterceptor extends LoggingInInterceptor {

	private MessageDAO messageDAO;

	@Override
	public void handleFault(Message message) {
		Exception content = message.getContent(Exception.class);

		StringBuilder sb = new StringBuilder("SoapFault\n\n");
		if (content instanceof SoapFault) {
			sb.append("Fault code: ");
			sb.append(((SoapFault) content).getFaultCode());
			sb.append("\n");
		}
		sb.append("Error message: ");
		sb.append(content.getLocalizedMessage());

		Map<String, Object> parts = new HashMap<String, Object>();
		parts.put(WsUtil.ID, Integer.parseInt((String) message.getExchange().get(LoggingMessage.ID_KEY)));
		parts.put(WsUtil.MISC, "");
		parts.put(WsUtil.PAYLOAD, sb.toString());
		parts.put("inbound", false);

		messageDAO.logMessage(parts);
	}

	@Override
	protected void log(Logger logger, String message) {
		Map<String, Object> parts = extractLogMessageParts(message);
		parts.put("inbound", true);
		messageDAO.logMessage(parts);
	}

	@Autowired
	public void setMessageDAO(MessageDAO messageDAO) {
		this.messageDAO = messageDAO;
	}
}
